package com.css.apps.base.user.action;

import cn.hutool.core.util.StrUtil;
import com.css.apps.base.common.Constants;
import com.css.apps.base.dict.service.DictMan;
import com.css.apps.base.org.model.SUserOrg;
import com.css.apps.base.security.model.SecurityParam;
import com.css.apps.base.security.service.SecurityService;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.po.UserFamilyPo;
import com.css.core.configuration.Environment;
import com.css.db.query.TransactionCache;
import com.css.util.*;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SuppressWarnings("serial")
public class InitUser extends UserAction {

	private static Log log = LogFactory.getLog(InitUser.class);

	private final String DEFAULT_ORGID = "ff8080817af114cc017af11830310003";//导入的默认orgID

	protected String userGo() {
		TransactionCache tx = null;
		try {
			String srcPath= DictMan.getDictType("d_import_file_path", "0").getName();
			System.out.println("------待导入文件夹路径为"+srcPath);
			//遍历人员任免表
			File srcfile = new File(srcPath);
			File[] fileArray = srcfile.listFiles();
			int totalnum = fileArray.length;
			int successnum = 0;
			int failnum=0;
			List<String> failFilepaths = new ArrayList<>(); //记录失败文件
			for (File file : fileArray) {
				try {
					//doc转table
					String[][] table2 = new WordUtil().getTableByword(file,2);
					String[][] table3 = new WordUtil().getTableByword(file,3);
                    //printTable(table2,table3);
                    //build suser、 userfamilyPo 、 sUserorg
                    String userId = UuidUtil.getUuid();
                    SUser userItem = buildUserItem(userId,table2,table3);
                    List<UserFamilyPo> userFamilyPoList = buildUserFamilyPoList(userId,table3);
                    SUserOrg userOrgItem = buildUserOrgItem(userId);
                    tx = new TransactionCache();
                    tx.save(userItem);
                    tx.save(userFamilyPoList);
                    tx.save(userOrgItem);
                    tx.commit();
					successnum++;
				}catch (Exception e){
                    if (tx != null) {
                        tx.rollback();
                    }
					failnum++;
					failFilepaths.add(file.getAbsolutePath());
					continue;
				}
			}
			System.out.println("----全部解析完毕------");
			System.out.println("本此总共解析了 【 "+totalnum +" 】 个人员简历");
			System.out.println("本此成功导入了 【 "+successnum +" 】 个人员简历");
			for (String failFilepath : failFilepaths) {
				System.out.println(failFilepath+"文件解析失败！--------------------------");
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return Action.SUCCESS;
		} catch (Exception ex) {
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			return Action.ERROR;
		}
	}

    /**
     * 输出调试
     * @param table1
     * @param table2
     */
	private void printTable(String[][] table1, String[][] table2){
	    for (int i=0;i<table1.length;i++){
            for (int j=0;j<table1[i].length;j++){
                if(StrUtil.isNotEmpty(table1[i][j])){
                    System.out.println(table1[i][j]+"  =====对应坐标===>  "+"["+i+","+j+"]");
                }
            }
        }
        for (int i=0;i<table2.length;i++){
            for (int j=0;j<table2[i].length;j++){
                if(StrUtil.isNotEmpty(table2[i][j])){
                    System.out.println(table2[i][j]+"  =====对应坐标===>  "+"["+i+","+j+"]");
                }
            }
        }
    }

    /**
     * 构建SuserOrg关联信息
     * @param userId
     * @return
     */
    private SUserOrg buildUserOrgItem(String userId) {
        SUserOrg sUserOrg = new SUserOrg();
        sUserOrg.setOrgId(DEFAULT_ORGID);
        sUserOrg.setDeptId(DEFAULT_ORGID);
        sUserOrg.setUserId(userId);
        return  sUserOrg;
    }

    /**
     * 构建Suser
     */
	private SUser buildUserItem(String userId, String[][] table1,String[][] table2){
        SUser item = new SUser();
        try {
            item.setUuid(userId);
            item.setRealName(table1[0][1]);
            String sex = DictMan.getDictCodeByName("d_sex",table1[0][3].trim());
            item.setSex(sex);
            //item.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(table1[0][5]));
            String nation = DictMan.getDictCodeByName("d_nation",table1[1][1].trim());
            item.setNation(nation);
            item.setNativeplace(table1[1][3]);
            item.setBirthplace(table1[1][5]);
            item.setJoinpartytime(new SimpleDateFormat("yyyy-mm").parse(table1[2][1]));
            item.setJoinworktime(new SimpleDateFormat("yyyy-mm").parse(table1[2][3]));
            item.setHealth(table1[2][5]);
            item.setProfessiontech_duty(table1[3][1]);
            item.setSkill(table1[3][3]);
            item.setFull_time_education(table1[4][2]);
            item.setFull_time_school_major(table1[4][4]);
            item.setOn_the_job_education(table1[6][2]);
            item.setOn_the_job_school_major(table1[6][4]);
            item.setCurrent_duty(table1[8][1]);
            item.setResume(table1[11][1]);
            item.setReward_and_punish(table2[0][1]);
            item.setExamine_conclusion(table2[1][1]);
            item.setOrgId(DEFAULT_ORGID);
            item.setOpenFlag(Constants.YES);
            item.setDelFlag(Environment.UN_DELETE_STATE);
            item.setIssueDate(new Date());
            item.setIssueId(sUser.getUserId());
            item.setIssueName(sUser.getRealName());
            item.setEditDate(new Date());
            item.setTotalLoginCount(0);
            item.setFailedLoginCount(0);
            String password = SecurityService.getParamValue(SecurityParam.INIT_PASSWORD);
            if (StringHelper.isEmpty(password)) {
                item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode("123456")));
            } else {
                item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode(password)));
            }
            item.setActiveStatus("3");
            item.setFailedLoginCount(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        return item;
    }

    //构建家庭成员
    private List<UserFamilyPo> buildUserFamilyPoList(String userId, String[][] table) throws ParseException {
	    List<UserFamilyPo> userFamilyPoList  = new ArrayList<>();
        for(int i=4; i<11; i++){
            //过滤掉空行人员
            boolean createFlag = false;
            for (int j=1;j<6;j++){
                if(StringHelper.isNotEmpty(table[i][j])){
                    createFlag = true;
                    break;
                }
            }
            if(createFlag){
                UserFamilyPo userFamilyPo = new UserFamilyPo();
                userFamilyPo.setUuid(UuidUtil.getUuid());
                userFamilyPo.setUserId(userId);
                userFamilyPo.setAppellation(table[i][1]);
                userFamilyPo.setMembername(table[i][2]);
                userFamilyPo.setBirthday(table[i][3]);
                userFamilyPo.setPoliticallandscape(table[i][4]);
                userFamilyPo.setUnitandposition(table[i][5]);
                userFamilyPoList.add(userFamilyPo);
            }
        }
	    return userFamilyPoList;
    }

}
